using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Acme.BookStore.StockManagement.Dtos.HuoPinPiCiGuanLian;
using Acme.BookStore.StockManagement.Services;
using AutoMapper;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Acme.BookStore.Repositories;

namespace Acme.BookStore.StockManagement
{
    /// <summary>
    /// 货品批次关联应用服务实现类
    /// </summary>
    public class HuoPinPiCiGuanLianAppService : ApplicationService, IHuoPinPiCiGuanLianAppService
    {
        private readonly IRepository<HuoPinPiCiGuanLian, int> _huoPinPiCiGuanLianRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="huoPinPiCiGuanLianRepository">货品批次关联仓储</param>
        /// <param name="mapper">对象映射</param>
        public HuoPinPiCiGuanLianAppService(
            IRepository<HuoPinPiCiGuanLian, int> huoPinPiCiGuanLianRepository,
            IMapper mapper)
        {
            _huoPinPiCiGuanLianRepository = huoPinPiCiGuanLianRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取货品批次关联分页列表
        /// </summary>
        /// <param name="input">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResultDto<HuoPinPiCiGuanLianDto>> GetListAsync(HuoPinPiCiGuanLianGetListInputDto input)
        {
            // 构建查询条件
            var query = _huoPinPiCiGuanLianRepository.GetQueryable();

            // 添加查询条件
            if (!string.IsNullOrEmpty(input.GoodsCodeOrName))
            {
                query = query.Where(x => x.GoodsCode.Contains(input.GoodsCodeOrName) || 
                                         x.GoodsName.Contains(input.GoodsCodeOrName));
            }

            if (!string.IsNullOrEmpty(input.GoodsType))
            {
                query = query.Where(x => x.GoodsType == input.GoodsType);
            }

            if (!string.IsNullOrEmpty(input.Unit))
            {
                query = query.Where(x => x.Unit == input.Unit);
            }

            if (!string.IsNullOrEmpty(input.Status))
            {
                query = query.Where(x => x.Status == input.Status);
            }

            if (!string.IsNullOrEmpty(input.WarehouseName))
            {
                query = query.Where(x => x.WarehouseName == input.WarehouseName);
            }

            if (!string.IsNullOrEmpty(input.BatchNumber))
            {
                query = query.Where(x => x.BatchNumber.Contains(input.BatchNumber));
            }

            if (!string.IsNullOrEmpty(input.GoodsCategory))
            {
                // 假设货品类别是根据货品类型的前缀来判断的
                query = query.Where(x => x.GoodsType.StartsWith(input.GoodsCategory));
            }

            // 剩余天数查询（假设是基于到期日期计算的）
            if (input.RemainingDaysMin.HasValue || input.RemainingDaysMax.HasValue)
            {
                var today = DateTime.Today;
                
                if (input.RemainingDaysMin.HasValue)
                {
                    var maxDate = today.AddDays(input.RemainingDaysMin.Value);
                    // 剩余天数大于等于最小值，意味着到期日期要大于等于 today + 最小天数
                    query = query.Where(x => x.ExpiryDate >= maxDate);
                }
                
                if (input.RemainingDaysMax.HasValue)
                {
                    var minDate = today.AddDays(input.RemainingDaysMax.Value);
                    // 剩余天数小于等于最大值，意味着到期日期要小于等于 today + 最大天数
                    query = query.Where(x => x.ExpiryDate <= minDate);
                }
            }

            // 获取总数
            var totalCount = await AsyncExecuter.CountAsync(query);

            // 排序
            if (!string.IsNullOrEmpty(input.Sorting))
            {
                query = query.OrderBy(x => x.Id);
            }
            else
            {
                query = query.OrderByDescending(x => x.Id);
            }

            // 分页
            query = query.Skip(input.SkipCount).Take(input.MaxResultCount);

            // 获取数据
            var items = await AsyncExecuter.ToListAsync(query);

            // 转换为DTO
            var dtos = _mapper.Map<List<HuoPinPiCiGuanLian>, List<HuoPinPiCiGuanLianDto>>(items);

            // 返回分页结果
            return new PagedResultDto<HuoPinPiCiGuanLianDto>(totalCount, dtos);
        }

        /// <summary>
        /// 获取货品批次关联详情
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns>货品批次关联</returns>
        public async Task<HuoPinPiCiGuanLianDto> GetAsync(int id)
        {
            var entity = await _huoPinPiCiGuanLianRepository.GetAsync(id);
            return _mapper.Map<HuoPinPiCiGuanLian, HuoPinPiCiGuanLianDto>(entity);
        }

        /// <summary>
        /// 创建货品批次关联
        /// </summary>
        /// <param name="input">货品批次关联</param>
        /// <returns>创建后的货品批次关联</returns>
        public async Task<HuoPinPiCiGuanLianDto> CreateAsync(HuoPinPiCiGuanLianDto input)
        {
            var entity = _mapper.Map<HuoPinPiCiGuanLianDto, HuoPinPiCiGuanLian>(input);
            entity = await _huoPinPiCiGuanLianRepository.InsertAsync(entity);
            return _mapper.Map<HuoPinPiCiGuanLian, HuoPinPiCiGuanLianDto>(entity);
        }

        /// <summary>
        /// 更新货品批次关联
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="input">货品批次关联</param>
        /// <returns>更新后的货品批次关联</returns>
        public async Task<HuoPinPiCiGuanLianDto> UpdateAsync(int id, HuoPinPiCiGuanLianDto input)
        {
            var entity = await _huoPinPiCiGuanLianRepository.GetAsync(id);
            _mapper.Map(input, entity);
            entity = await _huoPinPiCiGuanLianRepository.UpdateAsync(entity);
            return _mapper.Map<HuoPinPiCiGuanLian, HuoPinPiCiGuanLianDto>(entity);
        }

        /// <summary>
        /// 删除货品批次关联
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public async Task DeleteAsync(int id)
        {
            await _huoPinPiCiGuanLianRepository.DeleteAsync(id);
        }
    }
} 